# -*- coding: utf-8 -*-
from threading import Thread, Event
from config import CUSTOM_DATA_FILE_PATH, DATA_FILE_PATH, WECHAT_INDEX_FILE, IMAGE_FILE, CATEGORY, PKL_PATH, \
    WECHAT_TIME_SLOG
import xlrd
import os, datetime
import requests
from utils.TaoKeyUtil import get_tao_key
from wxpy import *


class WechatPoster(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.stopped = Event()
        self.bot = Bot(cache_path=PKL_PATH, console_qr=True)
        self.groups = self.bot.groups().search('白菜')

    def run(self):
        self.task_funtion()
        time = datetime.datetime.now()
        while not self.stopped.wait(WECHAT_TIME_SLOG) and time.hour > 8 and time.hour < 23:
            self.task_funtion()

    def stop(self):
        self.stopped.set()

    def task_funtion(self):
        if os.path.getmtime(DATA_FILE_PATH) > os.path.getmtime(CUSTOM_DATA_FILE_PATH):
            content, img = self.get_weibo_content()
        else:
            content, img = self.get_custom_data()
        headers = {"Accept": "text/html,application/xhtml+xml,application/xml;",
                   "Accept-Encoding": "gzip",
                   "Accept-Language": "zh-CN,zh;q=0.8",
                   "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
                   }
        response = requests.get(img, headers=headers)
        with open(IMAGE_FILE, 'wb') as f:
            f.write(response.content)
        f.close()

        for group in self.groups:
            group.send_image(IMAGE_FILE)
            group.send(content)

    def get_weibo_content(self):
        data = xlrd.open_workbook(DATA_FILE_PATH)
        table = data.sheets()[0]
        with open(WECHAT_INDEX_FILE, 'r') as f:
            start = int(f.read())
        for index in range(start, table.nrows):
            name = table.cell(index, 1).value
            img = table.cell(index, 2).value
            category = table.cell(index, 4).value
            nunmber = int(table.cell(index, 7).value)
            payback = float(table.cell(index, 8).value)
            platform = table.cell(index, 13).value
            try:
                a = category[:category.index('/')]
            except ValueError:
                a = category
            if platform == '天猫' and a in CATEGORY and nunmber > 500 and payback > 30:
                price = table.cell(index, 6).value
                card = table.cell(index, 17).value
                discount = table.cell(index, 21).value
                try:
                    after = round(float(price) - float(card[:card.index(u'元无条件券')]), 2)
                except ValueError:
                    after = round(float(price) - float(card[card.index(u'减') + 1:len(card) - 1]), 2)
                content = name + u'\n【在售价】：' + price + u'\n【券后价】：' + str(after) + u'\n复制这条消息，' + get_tao_key(name,
                                                                                                             discount,
                                                                                                             img) + u'，打开【手机淘宝】即可查看'
                with open(WECHAT_INDEX_FILE, 'w') as file:
                    file.write(str(index + 1))
                return content, img

    def get_custom_data(self):
        data = xlrd.open_workbook(CUSTOM_DATA_FILE_PATH)
        table = data.sheets()[0]
        with open(WECHAT_INDEX_FILE, 'r') as f:
            start = int(f.read())
        for index in range(start, table.nrows):
            name = table.cell(index, 1).value
            img = table.cell(index, 2).value

            price = table.cell(index, 5).value
            card = table.cell(index, 20).value
            key = table.cell(index, 24).value
            try:
                after = round(float(price) - float(card[:card.index(u'元无条件券')]), 2)
            except ValueError:
                after = round(float(price) - float(card[card.index(u'减') + 1:len(card) - 1]), 2)
            content = name + u'\n【在售价】：' + price + u'\n【券后价】：' + str(after) + u'\n复制这条消息，' + key + u'，打开【手机淘宝】即可查看'
            with open(WECHAT_INDEX_FILE, 'w') as file:
                file.write(str(index + 1))
                return content, img